import { defineStore } from 'pinia'
import { useStorage, type RemovableRef } from '@vueuse/core'
import { store } from '@/store'
import { getUserInfoApi, loginApi } from '@/server/user'
import type { LoginParamsType } from '@/server/user/interface'

interface UserInfo {
  roles: string[]
  perms: string[]
}
export const useUserStore = defineStore('user', () => {
  const user: UserInfo = {
    roles: [],
    perms: []
  }

  const token = useStorage('accessToken', '')

  const login = async (user: LoginParamsType) => {
    try {
      const res = await loginApi(user)
      const { data } = res
      const { tokenType, accessToken } = data
      // Bearer eyJhbGciOiJIUzI1NiJ9.xxx.xxx
      token.value = `${tokenType} ${accessToken}`
      return '登录成功'
    } catch (error) {
      return Promise.reject(error)
    }
  }

  const getUserInfo = async () => {
    try {
      const res = await getUserInfoApi()
      const { data } = res
      if (!data) {
        return Promise.reject(new Error('getUserInfo: data must be a non-null object!'))
      }
      if (!data.roles || data.roles.length <= 0) {
        return Promise.reject(new Error('getUserInfo: roles must be a non-null array!'))
      }
      Object.assign(user, { ...data })
      return data
    } catch (error) {
      return Promise.reject(error)
    }
  }

  const logout = async () => {
    token.value = ''
    window.location.reload() // 清空路由
  }

  return {
    user,
    token,
    login,
    getUserInfo,
    logout
  }
})

// 非setup
export function useUserStoreHook() {
  return useUserStore(store)
}
